package inferenceEngine.labels;

import java.util.ArrayList;
import java.util.HashMap;

/**
 * Collection of labels
 * Support quick access, quick search, quick add, but expensive remove.
 * @author YaoXiao
 *
 */
public class LabelCollection {

	private HashMap<String,Integer> labelNames = new HashMap<String,Integer>();
	private ArrayList<Label> collection = new ArrayList<Label>();
	
	public void add( Label l ){
		if( !labelNames.containsKey( l.getValue() ) ){
			collection.add(l);
			labelNames.put( l.getValue(), collection.size()-1 );
		}
	}
	
	public Label get( int i ){
		return collection.get(i);
	}
	
	public boolean contains( String label ){
		return labelNames.containsKey( label );
	}
	
	public void remove( String label ){
		int index = getIndex(label);
		labelNames.remove( label );
		collection.remove(index);
		freshLink();
	}
	
	private void freshLink() {
		labelNames.clear();
		for( int i=0; i<collection.size(); i++ ){
			labelNames.remove( collection.get(i).getValue() );
			labelNames.put(collection.get(i).getValue(), i);
		}
		
	}

	public int getIndex( String label ){
		return labelNames.get( label );
	}
	
	public int size(){
		return collection.size();
	}

	public void addAll(ArrayList<Label> results) {
		for( Label result : results ){
			add(result);
		}		
	}
}
